package com.yanqu.road.dao.impl.servercenter;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.entity.servercenter.ServerGroup;
import com.yanqu.road.utils.string.StringUtils;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ServerGroupDaoImpl extends TempDao {

    public void getServerGroupMap(Map<Integer, Map<Integer,ServerGroup>> channelServerGroupMap, Map<Integer,ServerGroup> serverGroupMap) {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_s_server_group order by groupId desc";
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                ServerGroup data = initServerGroup(rs);
                if(!channelServerGroupMap.containsKey(data.getChannelId())){
                    channelServerGroupMap.put(data.getChannelId(), new ConcurrentHashMap<>());
                }
                channelServerGroupMap.get(data.getChannelId()).put(data.getGroupId(), data);
                serverGroupMap.put(data.getGroupId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
    }

    private ServerGroup initServerGroup(ResultSet rs) throws SQLException {
        ServerGroup data = new ServerGroup();
        data.setGroupId(rs.getInt("groupId"));
        data.setChannelId(rs.getInt("channelId"));
        data.setCrossChat(rs.getBoolean("crossChat"));
        data.setCrossRank(rs.getBoolean("crossRank"));
        data.setCrossMammonState(rs.getInt("crossMammon"));
        String value = rs.getString("serverList");
        if(!StringUtils.isNullOrEmpty(value)){
            data.setServerListStr(value);
        }
        data.setServerList(StringUtils.stringToLongList(data.getServerListStr(), ","));
        return data;
    }
}
